<template>
  <div id="dialogChooseGoods">
    <el-dialog
      title="选择商品"
      width="1400px"
      :visible.sync="dialogData.isShow"
      :close-on-click-modal="false"
      @close="closeAddDialog"
      @submit.native.prevent
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <!-- 顶部搜索框部分 -->
          <div class="search-box">
            <el-form
              ref="ruleForm"
              :inline="true"
              :model="formInline"
              :rules="formRules"
            >
              <!-- 输入搜索部分 -->
              <el-form-item label="商品名称" prop="searchVal">
                <el-input
                  v-model="formInline.searchVal"
                  placeholder="请输入商品名称"
                  clearable
                ></el-input>
              </el-form-item>
              <el-form-item class="s-btn">
                <el-button
                  type="success"
                  icon="el-icon-search"
                  @click="toSearch('ruleForm')"
                >
                  查询
                </el-button>
                <el-button type="success" plain @click="reset">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <!-- 表格部分 -->
          <el-table
            v-loading="loading"
            :data="leftTableData"
            ref="leftTable"
            @select-all="handleSelectionAll"
            @select="selectionChange"
            height="490"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
              :selectable="selectAble"
            >
            </el-table-column>
            <el-table-column
              prop="goodsNumber"
              label="商品编号"
              width="150"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="type"
              label="商品类型"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <div>
                  <span v-if="scope.row.type">{{
                    scope.row.type | filterName('goods_type')
                  }}</span>
                  <span v-else>-</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="商品名称"
              align="center"
            ></el-table-column>
          </el-table>
        </el-col>
        <el-col :span="12">
          <!-- 顶部搜索框部分 -->
          <div class="search-box" style="height:55px;line-height:50px;">
            <span>已选商品（{{ totalRight }}/{{ maxSize }}）</span>
            <el-button
              type="warning"
              plain
              class="clear-btn"
              @click="cleanCheck"
            >
              清空全部
            </el-button>
          </div>
          <!-- 表格部分 -->
          <el-table
            v-loading="loadingRight"
            :data="rightTableData"
            height="490"
          >
            <el-table-column
              prop="goodsNumber"
              label="商品编号"
              width="150"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="type"
              label="商品类型"
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <div>
                  <span v-if="scope.row.type">{{
                    scope.row.type | filterName('goods_type')
                  }}</span>
                  <span v-else>-</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="商品名称"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" width="70">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  @click="delCheck(scope.row.goodsId, 'right')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页-全局组件-->
          <pageCom
            :searchParams="searchParamsRight"
            :total="totalRight"
            @searchList="searchListRight"
          ></pageCom>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="closeAddDialog"
          >取 消</el-button
        >
        <el-button
          type="success"
          :loading="confirmloading"
          @click="submitConfirm"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getGoodsList } from '@/api/activityCenter/activityManage/giveLessons' // 接口

export default {
  name: 'chooseGoodsDialog',
  msg: '赠课商品弹窗',
  props: ['dialogData'],
  data() {
    return {
      loading: false,
      loadingRight: false,
      confirmloading: false,
      totalRight: 0,
      leftTableData: [], // table内容
      rightTableData: [], // table已选课程
      checkData: [], // 所有已选课程
      searchParamsRight: {
        pageNum: 1, // 当前页数
        pageSize: 10 // 页面显示条数
      },
      formInline: {
        searchVal: ''
      },
      formRules: {
        searchVal: [
          {
            required: true,
            message: '商品名称不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 当前选中
      selectionId: [],
      maxSize: 20
    }
  },
  watch: {
    checkData: {
      handler(newV, oldV) {
        this.searchListRight()
      },
      deep: true
    }
  },
  mounted() {
    this.selectionId = this.dialogData.goodsList.map((item) => {
      return item.goodsId
    })
    this.checkData = this.dialogData.goodsList
    this.totalRight = this.selectionId.length
    this.tableShowSelect()
    if (this.totalRight > 0) {
      this.searchListRight()
    }
  },
  methods: {
    /* 获取列表 */
    searchList() {
      this.loading = true
      let obj = Object.assign({}, this.formInline)
      getGoodsList(
        obj,
        (response) => {
          this.loading = false
          this.leftTableData = response.rows
          this.total = response.total
          this.$nextTick(() => {
            this.tableShowSelect()
          })
        },
        (response) => {
          this.loading = false
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    },
    // 监听右侧列表更新分页
    searchListRight() {
      let obj = [...this.checkData]
      let start =
        (this.searchParamsRight.pageNum - 1) * this.searchParamsRight.pageSize
      let size = this.searchParamsRight.pageSize
      this.rightTableData = obj.splice(start, size)
    },
    // 搜索
    toSearch() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.searchList()
        }
      })
    },
    // 重置
    reset() {
      this.$refs['ruleForm'].resetFields()
    },
    // 确认导出
    submitConfirm() {
      this.$emit('setGoodsList', this.checkData)
      this.closeAddDialog()
    },
    // 弹窗关闭事件
    closeAddDialog() {
      this.loading = false
      this.dialogData.isShow = false
    },
    /* table选择(全选、取消全选使用) */
    handleSelectionAll(val) {
      // 全选（全部加入右侧）
      if (val.length + this.totalRight > this.maxSize) {
        this.$message.warning('最多可选择20个')
        this.$refs.leftTable.clearSelection()
        this.tableShowSelect()
        return
      }
      // 全选（全部加入右侧）
      if (val.length === this.leftTableData.length) {
        // 过滤出已存在的不再添加
        const addCourseData = val.filter(
          (item) => !this.selectionId.includes(item.goodsId)
        )
        this.addMultipleCheck(addCourseData)
      }
      // 反选（全部右侧检出）
      if (val.length === 0) {
        this.delMultipleCheck()
      }
    },
    /*手动勾选， 优化执行于handleSelectionChange方法*/
    selectionChange(selection, row) {
      let curId = row.goodsId
      if (this.selectionId.includes(curId)) {
        //已有，说明是减
        this.delCheck(curId, 'right')
      } else {
        //没有，说明是加
        this.addCheck(row)
      }
    },
    /*增加已选课程*/
    addCheck(row) {
      this.selectionId.push(row.goodsId)
      this.checkData.push(row)
      this.getRightTotal()
    },
    /*增加多个已选课程*/
    addMultipleCheck(rows) {
      const rowIds = rows.map((item) => {
        return item.goodsId
      })
      this.selectionId = [...this.selectionId, ...rowIds]
      this.checkData = [...this.checkData, ...rows]
      this.getRightTotal()
    },
    /*删除已选课程*/
    delCheck(goodsId) {
      let index = this.checkData.findIndex((item) => {
        return item.goodsId == goodsId
      })
      let indexId = this.selectionId.findIndex((item) => {
        return item == goodsId
      })
      if (index >= 0) {
        this.checkData.splice(index, 1)
        this.selectionId.splice(indexId, 1)
        this.getRightTotal()
        this.changeChooseLeft(goodsId, false)
        this.searchListRight()
      }
    },
    /*删除多个已选课程*/
    delMultipleCheck() {
      let checkData = this.checkData
      const leftDataIds = this.leftTableData.map((item) => {
        return item.goodsId
      })
      let newCheckData = checkData.filter(
        (item) => !leftDataIds.includes(item.goodsId)
      )
      this.selectionId = newCheckData.map((item) => {
        return item.goodsId
      })
      this.checkData = newCheckData
      this.getRightTotal()
      this.searchListRight()
    },
    getRightTotal() {
      this.totalRight = this.checkData.length
    },
    /*左侧列表数据回填(删除/新增)*/
    changeChooseLeft(goodsId, flog) {
      let index = this.leftTableData.findIndex((item) => {
        return item.goodsId == goodsId
      })
      if (index >= 0) {
        let row = this.leftTableData[index]
        this.$refs.leftTable.toggleRowSelection(row, flog)
      }
    },
    /*获取列表数据后，数据回填*/
    tableShowSelect(flog = true) {
      for (let [index, item] of this.leftTableData.entries()) {
        let goodsId = item.goodsId
        if (this.selectionId.includes(goodsId)) {
          let row = this.leftTableData[index]
          this.$refs.leftTable.toggleRowSelection(row, flog)
        }
      }
    },
    // 右侧全部清空
    cleanCheck() {
      this.tableShowSelect(false)
      this.checkData = []
      this.selectionId = []
      this.rightTableData = []
      this.getRightTotal()
    },
    // 超出最大限制禁止选中
    selectAble(row, index) {
      let isSelect = this.selectionId.includes(row.goodsId)
      return (
        this.totalRight < this.maxSize ||
        (this.totalRight >= this.maxSize && isSelect)
      )
    }
  }
}
</script>

<style lang="less">
#dialogChooseGoods {
  .clear-btn {
    margin-top: 15px;
    float: right;
  }
  .search-box {
    padding: 0 0 10px !important;
    overflow: hidden;
  }
  .el-table {
    .el-button {
      padding: 0 0px;
    }
  }
  .img-box {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 50px;
    border: 1px solid #ddd;
    .el-image {
      width: 100%;
      height: 100%;
    }
    img {
      max-width: 100%;
      max-height: 100%;
      cursor: pointer;
    }
  }
}
</style>
